package com.swf.seed.xml.jaxb.monitor;

import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class JaxbUtil {
	@SuppressWarnings("unchecked")
	public static <T> T xml2Bean(String xml,Class<T> t){
  		T bean=null ;
  		JAXBContext jaxbContext;
  		try {
			jaxbContext = JAXBContext.newInstance(t);
			Unmarshaller um = jaxbContext.createUnmarshaller();
			StreamSource streamSource = new StreamSource(new StringReader(xml));
			bean = (T) um.unmarshal(streamSource);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  		 return bean;
  	 }
 	public static <T> String bean2Xml(T bean,Map<String,Object> map){
  		JAXBContext jaxbContext;
  		StringWriter sw = new StringWriter();
  		try {
  			jaxbContext = JAXBContext.newInstance(bean.getClass());
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			for (Map.Entry<String,Object> entry:map.entrySet()){
				jaxbMarshaller.setProperty(entry.getKey(), entry.getValue());
			}
			jaxbMarshaller.marshal(bean, sw);
  		} catch (JAXBException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		}
  		return sw.toString();
  	}
  	
  	public static <T> String bean2Xml(T bean){
  		return bean2Xml(bean, new HashMap<String,Object>());
  	}
  	
  	
  	
  	public static void main(String[] args) throws InterruptedException {
  		MonitorManager monitor = new MonitorManager();
		MFile m = new MFile();
		m.setName("c");
		m.setTime(new Date());
		MFile m1 = new MFile();
		m1.setName("d");
		m1.setTime(new Date());
		TimeUnit.SECONDS.sleep(2);
		MFile m3 = new MFile();
		m3.setName("d");
		m3.setTime(new Date());
		
		monitor.getFileMonitor().add(m);
		monitor.getFileMonitor().add(m1);
		monitor.getFileMonitor().add(m3);
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put(Marshaller.JAXB_ENCODING, "GBK");
		map.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		String xml = bean2Xml(monitor,map);
		System.out.println(xml);
		MonitorManager mm = xml2Bean(xml, MonitorManager.class);
		System.out.println(mm);
		String sd1= "2014-09-13 17:55:22";
		String sd2= "2014-09-13 17:55:24";
		String pattern = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat fmt =new SimpleDateFormat(pattern);
	}
}
